package com.aiwu.pop;

import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;

import com.aiwu.PrefsHelper;
import com.aiwu.bean.ScreenConfig;
import com.aiwu.library.ui.widget.transformerstip.TransformersTip;
import com.aiwu.library.ui.widget.transformerstip.gravity.TipGravity;
import com.aiwu.library.util.DisplayUtil;
import com.aiwu.library.util.ToastUtil;
import com.aiwu.widget.ConstraintHeightListView;

import org.citra.citra_emu.R;
import org.citra.citra_emu.activities.EmulationActivity;

import java.util.ArrayList;
import java.util.List;

/**
 * 快速切换布局
 */
public class QuickScreenLayoutDialog extends AlertDialog implements View.OnClickListener {
    private final FastSettingDialog fastSettingDialog;
    private final TextView[] tvs;
    private final int[] layoutIds;

    public QuickScreenLayoutDialog(EmulationActivity context, FastSettingDialog fastSettingDialog) {
        super(context, R.style.AiWuDialog);
        this.fastSettingDialog = fastSettingDialog;
        layoutIds = new int[]{-1, -1};
        tvs = new TextView[2];
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init();
    }

    private void init() {
        setContentView(R.layout.dialog_quick_screen_layout);
        setCancelable(true);
        setCanceledOnTouchOutside(true);
        initView();
    }

    private void initView() {
        findViewById(R.id.screen_layout_first).setOnClickListener(this);
        findViewById(R.id.screen_layout_second).setOnClickListener(this);
        findViewById(R.id.btn_confirm).setOnClickListener(this);
        tvs[0] = findViewById(R.id.tv_screen_layout_first);
        tvs[1] = findViewById(R.id.tv_screen_layout_second);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.screen_layout_first) {
            showPop(v, 0);
        } else if (v.getId() == R.id.screen_layout_second) {
            showPop(v, 1);
        } else if (v.getId() == R.id.btn_confirm) {
            saveLayout();
        }
    }

    private void saveLayout() {
        for (int id : layoutIds) {
            if (id == -1) {
                ToastUtil.toast(R.string.not_choose_screen_layout);
                return;
            }
        }
        PrefsHelper.getInstance().setQuickScreenLayout(layoutIds[0], layoutIds[1]);
        fastSettingDialog.cbQuickScreenLayout.setChecked(true);
        dismiss();
    }

    private void showPop(View anchorView, int layoutPosition) {
        int maxHeight = getContext().getResources().getDimensionPixelOffset(R.dimen.qb_px_200);
        final ConstraintHeightListView listView = new ConstraintHeightListView(getContext(), maxHeight);
        listView.setDivider(new ColorDrawable(getContext().getColor(R.color.stroke_2)));
        listView.setDividerHeight(1);
        listView.setSelector(new ColorDrawable());
        new TransformersTip(anchorView, listView) {
            @Override
            protected void initView(View contentView) {
                if (contentView instanceof ListView) {
                    LayoutAdapter adapter = new LayoutAdapter(getConfigList());
                    ((ListView) contentView).setAdapter(adapter);
                    listView.setOnItemClickListener((parent, view, position, id) -> {
                        ScreenConfig item = adapter.getItem(position);
                        if (item != null) {
                            selectedLayout(layoutPosition, item.getId(), item.getName());
                        }
                        dismissTip();
                    });
                }
            }
        }.setTipGravity(TipGravity.TO_BOTTOM_CENTER)
                .setBgColorRes(R.color.bg_dialog_title)
                .setArrowHeightDp(0)
                .setBackgroundDimEnabled(false)
                .setDismissOnTouchOutside(true)
                .setFixedWidth(anchorView.getWidth())
                .show();
    }

    private void selectedLayout(int layoutPosition, int layoutId, String name) {
        layoutIds[layoutPosition] = layoutId;
        tvs[layoutPosition].setText(name);
        //防止重复
        for (int i = 0; i < layoutIds.length; i++) {
            if (i != layoutPosition && layoutIds[i] == layoutId) {
                layoutIds[i] = -1;
                tvs[i].setText("");
            }
        }
    }

    private List<ScreenConfig> getConfigList() {
        List<ScreenConfig> screenConfigs = new ArrayList<>();
        int startId, endId;
        if (DisplayUtil.isLandscape()) {
            //横屏要加上4个配置
            for (int type : SwitchScreenLayoutDialog.LAYOUT_OPTIONS) {
                ScreenConfig config = SwitchScreenLayoutDialog.createConfigByType(type);
                screenConfigs.add(config);
            }
            startId = PrefsHelper.SCREEN_CONFIG_ID_LANDSCAPE_START;
            endId = PrefsHelper.SCREEN_CONFIG_ID_LANDSCAPE_END;
        } else {
            //横屏要加上1个配置
            ScreenConfig config = SwitchScreenLayoutDialog.createConfigByType(SwitchScreenLayoutDialog.LAYOUT_OPTIONS[0]);
            screenConfigs.add(config);
            startId = PrefsHelper.SCREEN_CONFIG_ID_PORTRAIT_START;
            endId = PrefsHelper.SCREEN_CONFIG_ID_PORTRAIT_END;
        }
        for (int i = startId; i <= endId; i++) {
            ScreenConfig config = PrefsHelper.getInstance().getScreenConfig(i);
            if (config == null) {
                continue;
            }
            screenConfigs.add(config);
        }
        return screenConfigs;
    }

    static class LayoutAdapter extends BaseAdapter {
        private final List<ScreenConfig> mData;

        public LayoutAdapter(List<ScreenConfig> mData) {
            this.mData = mData;
        }

        @Override
        public int getCount() {
            return mData == null ? 0 : mData.size();
        }

        @Override
        public ScreenConfig getItem(int position) {
            return mData == null ? null : mData.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            final Context context = parent.getContext();
            ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = LayoutInflater.from(context).inflate(R.layout.item_quick_screen_layout, null);
                holder.tv = convertView.findViewById(R.id.tv);
                convertView.setTag(holder);
            }
            holder = (ViewHolder) convertView.getTag();
            final ScreenConfig item = getItem(position);
            holder.tv.setText(item.getName());
            return convertView;
        }

        static class ViewHolder {
            TextView tv;
        }
    }
}
